package org.pnp.services;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.pnp.main.MainActivity;
import org.pnp.main.R;
import org.pnp.util.StockAnalysisHelper;
import org.pnp.util.StringParser;
import org.pnp.vo.Stock;
import org.pnp.vo.StockConfigration;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class BackGroundService extends Service {
	private static final String TAG = "BackGroundService";
	private String urlStr = "http://idc-hq-tj.sinajs.cn/list=";
	StockAnalysisHelper helper; 
	private NotificationManager mNotificationManager;
	private Timer timer = new Timer();
	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				doAnalysis(urlStr);
				break;
			}
			super.handleMessage(msg);
		}

	};
	TimerTask task = new TimerTask() {

		public void run() {
				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
		}

	};
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	public void onCreate(){
		//initialize the variable
		Log.d(TAG, "Service is on Creating");
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		helper = new StockAnalysisHelper(this);
		String allStockCodes = helper.getAllStockCodes();
		this.urlStr = "http://idc-hq-tj.sinajs.cn/list=" +allStockCodes;
	}
	
	public void onStart(Intent intent, int startId){
		Log.d(TAG,"Service started");
		//start the timer to get the stock information from sina website
		timer.schedule(task,1000, 10000);
	}
	
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.d(TAG,"Service Destroy");
		timer.cancel();
		super.onDestroy();
	}
	
	private synchronized void doAnalysis(String urlStr){

		Stock stock;
		String stockCode;
		
		Map<String, StockConfigration> persistStocks = helper.getAllStockConfigs();
		Map<String, Stock> stockInfos = helper.getStockInfo(urlStr);
		StockConfigration stockConfig;
		
		
		double currentPrice;
		double highWarnPrice;
		double lowWarnPrice;
		
		Set<String> stockcodes = stockInfos.keySet();
		Iterator<String> it = stockcodes.iterator();
		while(it.hasNext()){
			stockCode =  it.next();
			stockConfig = persistStocks.get(stockCode);
			stock = stockInfos.get(stockCode);
			//begin to compare the setting value with current price
			highWarnPrice = stockConfig.getHighWarnPrice();
			lowWarnPrice = stockConfig.getLowWarnPrice();
			currentPrice = stock.getCurrentPrice();
			if(currentPrice >= highWarnPrice ){
				System.out.println("UP");
				playNotifies("Stock:"+stock.getStockName(), stock.getStockName()+" is higher than High Warn Pirce now", R.drawable.sun, Notification.DEFAULT_ALL);
			}
			if(currentPrice <= lowWarnPrice){
				System.out.println("DOWN");
				playNotifies("Stock:"+stock.getStockName(), stock.getStockName()+" is lower than Low Warn Pirce now", R.drawable.cloudy , Notification.DEFAULT_ALL);
			}
		}
		
	}
	
	private void playNotifies(String title, String content, int drawable, int defaults){
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, MainActivity.class), 0);

		

		final Notification notification = new Notification(drawable,
				content, System.currentTimeMillis());

		notification.setLatestEventInfo(this, title, content, contentIntent);
		//notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
		//notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
		notification.defaults = defaults;
		notification.number++;

		mNotificationManager.notify(1, notification);
		//isTurnOn = true;
	}
}
